package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.constant.RedisConstant;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.entity.Result;
import com.atguigu.pojo.Setmeal;
import com.atguigu.pojo.TravelGroup;

import com.atguigu.service.SetmealService;
import com.atguigu.service.TravelGroupService;

import com.atguigu.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.UUID;

@RestController
@RequestMapping("/Setmeal")
public class SetmealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    SetmealService setmealService;
        @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
            try {
                //获取原始文件名
                String originalFilename = imgFile.getOriginalFilename();//获取web端的图片信息 ns.jpg
                String ext = originalFilename.substring(originalFilename.indexOf("."));// .jsp
                String newFileName = UUID.randomUUID().toString() + ext;
                //文件上传，防止文件名称同名，难道已上传文件，每次上传都需要生成新的动态名称
                QiniuUtils.upload2Qiniu(imgFile.getBytes(),newFileName);
                System.out.println("上传到七牛云的文件名称: " +newFileName);
                //图片上传成功
                //===2021-4-1 下午补充代码，解决垃圾图片清理问题===
                jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, newFileName);
                //-----------------------------------------------
                //将上传图片名称存入Redis，基于Redis的Set结合存储

                return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,newFileName);


            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
            }
        }
@RequestMapping("/add")
    public Result add(Integer[] travelgroupIds, @RequestBody Setmeal setmeal) {
    try {
        setmealService.add(setmeal, travelgroupIds);
        return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);

    }
}
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = setmealService.findPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        return pageResult;
    }
}


